package com.lzx.adx.report.controller.v3;

import com.alibaba.fastjson.JSON;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.cache.OcpxAccountLocalCache;
import com.lzx.adx.report.constant.StatusConstant;
import com.lzx.adx.report.controller.v2.AbstractController;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.model.common.CommonReportRequest;
import com.lzx.adx.report.support.ReportMappingFactory;
import com.lzx.adx.report.support.strategy.mpping.AbstractReportParamsMapping;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

@RequestMapping("/wt/api")
@RestController
@Slf4j
@RequiredArgsConstructor
public class CommonReportV3Controller extends AbstractV3Controller {

    @GetMapping("/report")
    public ResponseEntity report(@RequestParam Map<String,Object> params, HttpServletRequest request){

        log.info("上报的原始请求参数为{}", JSON.toJSONString(params));
        if(!params.containsKey("dspId") && Objects.isNull(params.get("dspId"))){
            log.error("参数非法，确实核心关键字段");
            return  ResponseEntity.badRequest().body(new Result());
        }
        String dspId= String.valueOf(params.get("dspId"));
        OcpxAccountDTO accountDTO = OcpxAccountLocalCache.getInstance().get(dspId);
        if(accountDTO.getStatus().equals(StatusConstant.DISABLE)){
            return ResponseEntity.ok(new Result(Result.account_stop,"账户已停用请联系商务处理"));
        }



        AbstractReportParamsMapping reportParamsMapping= ReportMappingFactory.handler(accountDTO.getMediaChannel());
        CommonReportRequest adapter = reportParamsMapping.adapter(params);
        reportBase(adapter);

        return ResponseEntity.ok(new Result());
    }


    /**
     * @param allParams 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/callback")
    public ResponseEntity callback(@RequestParam Map<String,String> allParams) throws Exception {

        return  baseCallback(allParams);
    }

}
